package com.innovation.chengzhangriji.ui.widget;

import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.innovation.chengzhangriji.util.FileUtils;
import com.innovation.chengzhangriji.util.Size;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DiscoverPhotoViewHolder extends DiscoverViewHolder {

    public interface OnClickPhotoListener {

        void onClickPhoto(DiscoverPhotoViewHolder holder, int position);

    }

    private OnClickPhotoListener onClickPhotoListener;

    private TextView textPhotoContent;

    private TextView textPhotoLabel;

    // private ImageView[] imagePhotos;
    private RelativeLayout photoLayout;

    public DiscoverPhotoViewHolder(View itemView) {
        super(itemView);
        View view = LayoutInflater.from(itemView.getContext()).inflate(R.layout.item_discover_photo, getContent());
        textPhotoContent = (TextView) view.findViewById(R.id.text_content);
        textPhotoLabel = (TextView) view.findViewById(R.id.text_label);
//        imagePhotos = new ImageView[6];
//        imagePhotos[0] = (ImageView) view.findViewById(R.id.image_photo_1);
//        imagePhotos[1] = (ImageView) view.findViewById(R.id.image_photo_2);
//        imagePhotos[2] = (ImageView) view.findViewById(R.id.image_photo_3);
//        imagePhotos[3] = (ImageView) view.findViewById(R.id.image_photo_4);
//        imagePhotos[4] = (ImageView) view.findViewById(R.id.image_photo_5);
//        imagePhotos[5] = (ImageView) view.findViewById(R.id.image_photo_6);
//        for (ImageView imagePhoto : imagePhotos) {
//            imagePhoto.setOnClickListener(this);
//        }
        photoLayout = (RelativeLayout) view.findViewById(R.id.photo_layout);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (onClickPhotoListener == null) {
            return;
        }
//        int index = -1;
//        switch (v.getId()) {
//            case R.id.image_photo_1:
//                index = 0;
//                break;
//            case R.id.image_photo_2:
//                index = 1;
//                break;
//            case R.id.image_photo_3:
//                index = 2;
//                break;
//            case R.id.image_photo_4:
//                index = 3;
//                break;
//            case R.id.image_photo_5:
//                index = 4;
//                break;
//            case R.id.image_photo_6:
//                index = 5;
//                break;
//        }
//        if (index == -1) {
//            return;
//        }
        if(v.getTag() != null) {
            onClickPhotoListener.onClickPhoto(this, Integer.parseInt(v.getTag().toString()));
        }
    }

    public void setOnClickPhotoListener(OnClickPhotoListener onClickPhotoListener) {
        this.onClickPhotoListener = onClickPhotoListener;
    }

    public void setPhotoContent(String content) {
        if (TextUtils.isEmpty(content)) {
            textPhotoContent.setVisibility(View.GONE);
        } else {
            textPhotoContent.setVisibility(View.VISIBLE);
            textPhotoContent.setText(content);
        }
    }

    public void setPhotoLabel(String label) {
        if (TextUtils.isEmpty(label)) {
            textPhotoLabel.setVisibility(View.GONE);
        } else {
            textPhotoLabel.setVisibility(View.VISIBLE);
            textPhotoLabel.setText(label);
        }
    }

    public void setPhotoUrl(String[] urls) {
        photoLayout.removeAllViews();
//        for (int i = 0; i < 9; i++) {
//            imagePhotos[i].setVisibility(View.GONE);
//        }
        if (urls == null) {
            return;
        }
        if(urls.length == 1) {
            ImageView imageView = addImageView(0);
            imageView.setOnClickListener(this);

            // 图片解析，设置图片的大小
            Size size = null;
            if(urls[0].startsWith("/")) {
                size = FileUtils.decodeImageSize(urls[0]);
            }
            else {
                File imgFile = ImageLoader.getInstance().getDiskCache().get(Config.createSizeUrl(urls[0], 480));
                if((imgFile != null && imgFile.exists())) {
                    size = FileUtils.decodeImageSize(imgFile.getPath());
                }
                else {
                    size = requestImageSize(Config.createSizeUrl(urls[0], 480));
                }
            }
            if(size != null && size.getWidth() != 0 && size.getHeight() != 0) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                float width = -1, height = -1;
                // System.out.println("content-width:"+ getContentWidth());
                if(size.getWidth() >= size.getHeight()) {
                    width = (int)(getContentWidth() * 2.0f / 3);
                } else {
                    width = (int)(getContentWidth() / 3.0f);
                }
                Log.i("System.out", "image-width:" + width);
                height = width * size.getHeight() / size.getWidth();
                Log.i("System.out", "image-height:" + height);
                float maxHeight = ChZhRJUtils.dp2px(327.0f / 2, itemView.getResources().getDisplayMetrics());
                if(height > maxHeight) {
                    height = maxHeight;
                    width = height * size.getWidth() / size.getHeight();
                }
                params.width = (int) width;
                params.height = (int) height;
                imageView.setLayoutParams(params);
            }
            if(urls[0].startsWith("/")) {
                ImageLoader.getInstance().displayImage("file://" + urls[0], imageView, Config.getOptionsPhoto());
            } else {
                ImageLoader.getInstance().displayImage(Config.createSizeUrl(urls[0], 480), imageView, Config.getOptionsPhoto());
            }
        } else {
            for (int i = 0; i < urls.length; i++) {
                if (!TextUtils.isEmpty(urls[i])) {
                    // imagePhotos[i].setVisibility(View.VISIBLE);
                    ImageView imageView = addImageView(i);
                    imageView.setOnClickListener(this);
                    ImageLoader.getInstance().displayImage(Config.createSizeUrl(urls[i], 480), imageView, Config.getOptionsPhoto());
                }
            }
        }
    }

    /**
     * 下载图片大小
     * @param url
     */
    public Size requestImageSize(String uri) {
        Size size = null;
        try {
            if(!Client.isNetworkConnect(itemView.getContext())) {
                return size;
            }
            URL url = new URL(uri);
            // System.out.println("url:" + uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=0-255");
            connection.setReadTimeout(1000);
            InputStream stream = connection.getInputStream();
            byte[] buffer = new byte[256];
            stream.read(buffer);
            connection.disconnect();
            size = FileUtils.decodeImageSize(buffer);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return size;
    }

    // 添加 ImageView
    public ImageView addImageView(int i) {
        ImageView imageView = new ImageView(photoLayout.getContext());
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        int size = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 84, photoLayout.getContext().getResources().getDisplayMetrics());
        int marginSize = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 92, photoLayout.getContext().getResources().getDisplayMetrics());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(size, size);
        params.setMargins((i % 3) * marginSize, (i / 3) * marginSize, 0, 0);
        imageView.setLayoutParams(params);
        imageView.setTag(i);
        photoLayout.addView(imageView);
        return imageView;
    }
}
